// GazePointEvaluation.cpp : Defines the entry point for the application.
//

#include "stdafx.h"
#include "GazePointEvaluation.h"

#define MAX_LOADSTRING 100

// Global Variables:
HINSTANCE hInst;								// current instance
TCHAR szTitle[MAX_LOADSTRING];					// The title bar text
TCHAR szWindowClass[MAX_LOADSTRING];			// the main window class name
//GDI Variables
GdiplusStartupInput gdiplusStartupInput;
ULONG_PTR           gdiplusToken;

//Trackers
EyeTracker eye_tracker;
HeadTracker head_tracker;

//Head Tracker return rect
CvRect head_rect;
	
//Screen Resolution rect
RECT rc;

//Eye coordinates
int eye_x = 0; int eye_y = 0;

//Initial Head coordinates
float init_head_x=0.0;
float init_head_y=0.0;

//Crosshair coordinates
int crosshair_x = 100; int crosshair_y = 100;

// Forward declarations of functions included in this code module:
ATOM				MyRegisterClass(HINSTANCE hInstance);
BOOL				InitInstance(HINSTANCE, int);
LRESULT CALLBACK	WndProc(HWND, UINT, WPARAM, LPARAM);
INT_PTR CALLBACK	About(HWND, UINT, WPARAM, LPARAM);

//Keyboard handles
INPUT_RECORD event_buffer;
DWORD num;

//Get eye coordinate function
//Sets eye_x & eye_y
double eye_tracker_x=0.0; //x coordianate of eye
double eye_tracker_y=0.0; //y coordianate of eye 
	
double head_x=0.0; //x coordianate of head
double head_y=0.0; //y coordianate of head 
	
double offset_x = 0.0; //offset in x axis
double offset_y = 0.0; //offset in y axis
	
double corrected_eye_x = 0.0; // new eye x coordiante with offsets
double corrected_eye_y = 0.0; // new eye y coordiante with offsets

void set_eye_coordinates()
{
	while(true)
	{

		EyeTracker::return_struct result = eye_tracker.get_coordinate();
		head_rect = head_tracker.get_rectangle();

		eye_tracker_x = result.x;
		eye_tracker_y = result.y;

		head_x = head_rect.x;
		head_y = head_rect.y;

		offset_x = head_x - init_head_x;
		offset_y = head_y - init_head_y;
		
		//TODO: Check for other offset calculations
		corrected_eye_x = eye_tracker_x + offset_x;
		corrected_eye_y = eye_tracker_y + offset_y;
		
		eye_x = (int)corrected_eye_x;
		eye_y = (int)corrected_eye_y;

	}
}


//Paint Function
void MyOnPaint(HDC hdc)
{
	
	Graphics graphics(hdc);
	Pen pen(Color::Blue);
	const int crosshair_circle_diameter = 24;
	
	int x = crosshair_x; int y=crosshair_y;

	Point point_x1(x-10, y); Point point_x2(x+10, y);
	Point point_y1(x, y+10); Point point_y2(x, y-10);
	
	//draw crosshair
	graphics.DrawLine(&pen, point_x1, point_x2);
	graphics.DrawLine(&pen, point_y1, point_y2);
	graphics.DrawEllipse(&pen, x-crosshair_circle_diameter/2,y-crosshair_circle_diameter/2,crosshair_circle_diameter,crosshair_circle_diameter);

}


int APIENTRY _tWinMain(HINSTANCE hInstance,
                     HINSTANCE hPrevInstance,
                     LPTSTR    lpCmdLine,
                     int       nCmdShow)
{
	UNREFERENCED_PARAMETER(hPrevInstance);
	UNREFERENCED_PARAMETER(lpCmdLine);

 	// TODO: Place code here.
	MSG msg;
	HACCEL hAccelTable;
	
	// Initialize global strings
	LoadString(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING);
	LoadString(hInstance, IDC_GAZEPOINTEVALUATION, szWindowClass, MAX_LOADSTRING);
	MyRegisterClass(hInstance);
	//Initialze GDI++
	GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);
	//Get Screen Resolution
	GetWindowRect(GetDesktopWindow(), &rc);

	//Initialize trackers
	//init eye tracker
	eye_tracker = EyeTracker::EyeTracker(); 
	int init_eye = eye_tracker.init();
	
	//init Head tracker
	head_tracker = HeadTracker::HeadTracker();
	head_tracker.set_Max_HSV(130, 240, 124);
	head_tracker.set_Min_HSV(104, 178, 70);
	head_tracker.set_thresh_size(70);
	int init_head = head_tracker.init();

	//get initial average head point
	int sum_x=0; int sum_y=0;
	//for(int i=10000; i>0; i--){
	//	head_rect = head_tracker.get_rectangle();
	//	sum_x += head_rect.x;
	//	sum_y += head_rect.y;
	//}
	
	init_head_x = sum_x/10000.0; //initial head coordiante of x
	init_head_y = sum_y/10000.0; //initial head coordiante of y
	
	//Calibrate
	CommandClient command = CommandClient::CommandClient();
	int i = command.send_command("CAL_START");

	// Perform application initialization:
	if (!InitInstance (hInstance, nCmdShow))
	{
		return FALSE;
	}

	hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_GAZEPOINTEVALUATION));

	/*Start threads*/
	using namespace boost;
	//Init eyetracking thread
	thread eye_tracking_thread(set_eye_coordinates);

	while (GetMessage(&msg, NULL, 0, 0))
	{
		if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg))
		{
			TranslateMessage(&msg);
			DispatchMessage(&msg);
		}
	}
	
	return (int) msg.wParam;
}


//
//  FUNCTION: MyRegisterClass()
//
//  PURPOSE: Registers the window class.
//
//  COMMENTS:
//
//    This function and its usage are only necessary if you want this code
//    to be compatible with Win32 systems prior to the 'RegisterClassEx'
//    function that was added to Windows 95. It is important to call this function
//    so that the application will get 'well formed' small icons associated
//    with it.
//
ATOM MyRegisterClass(HINSTANCE hInstance)
{
	WNDCLASSEX wcex;

	wcex.cbSize = sizeof(WNDCLASSEX);

	wcex.style			= CS_HREDRAW | CS_VREDRAW;
	wcex.lpfnWndProc	= WndProc;
	wcex.cbClsExtra		= 0;
	wcex.cbWndExtra		= 0;
	wcex.hInstance		= hInstance;
	wcex.hIcon			= LoadIcon(hInstance, MAKEINTRESOURCE(IDI_GAZEPOINTEVALUATION));
	wcex.hCursor		= LoadCursor(NULL, IDC_ARROW);
	wcex.hbrBackground	= (HBRUSH)(COLOR_WINDOW+1);
	wcex.lpszMenuName	= MAKEINTRESOURCE(IDC_GAZEPOINTEVALUATION);
	wcex.lpszClassName	= szWindowClass;
	wcex.hIconSm		= LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL));

	return RegisterClassEx(&wcex);
}

//
//   FUNCTION: InitInstance(HINSTANCE, int)
//
//   PURPOSE: Saves instance handle and creates main window
//
//   COMMENTS:
//
//        In this function, we save the instance handle in a global variable and
//        create and display the main program window.
//
BOOL InitInstance(HINSTANCE hInstance, int nCmdShow)
{
   HWND hWnd;

   hInst = hInstance; // Store instance handle in our global variable
   hWnd = CreateWindow(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW,
	   0, 0, rc.right, rc.right, NULL, NULL, hInstance, NULL);

   if (!hWnd)
   {
      return FALSE;
   }

   ShowWindow(hWnd, nCmdShow);
   UpdateWindow(hWnd);

   return TRUE;
}

//
//  FUNCTION: WndProc(HWND, UINT, WPARAM, LPARAM)
//
//  PURPOSE:  Processes messages for the main window.
//
//  WM_COMMAND	- process the application menu
//  WM_PAINT	- Paint the main window
//  WM_DESTROY	- post a quit message and return
//
//
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
	int wmId, wmEvent;
	PAINTSTRUCT ps;
	HDC hdc;

	switch (message)
	{
	case WM_COMMAND:
		wmId    = LOWORD(wParam);
		wmEvent = HIWORD(wParam);
		// Parse the menu selections:
		switch (wmId)
		{
		case IDM_ABOUT:
			DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About);
			break;
		case IDM_EXIT:
			//Shutdown GDI
			GdiplusShutdown(gdiplusToken);
			DestroyWindow(hWnd);
			break;
		default:
			return DefWindowProc(hWnd, message, wParam, lParam);
		}
		break;
	case WM_KEYDOWN:
		InvalidateRect(hWnd, NULL, true);
		switch(wParam)
		{
			case VK_UP:    
				crosshair_y -= 15;
				break;
			case VK_DOWN:   
				crosshair_y += 15;
				break;
			case VK_LEFT:  
				crosshair_x -= 15;
				break;
			case VK_RIGHT: 
				crosshair_x += 15;
				break;
			//default: break;
		}
	case WM_PAINT:
		hdc = BeginPaint(hWnd, &ps);
		// TODO: Add any drawing code here...
		MyOnPaint(hdc);
		EndPaint(hWnd, &ps);
		break;
	case WM_DESTROY:
		PostQuitMessage(0);
		break;
	
	default:
		return DefWindowProc(hWnd, message, wParam, lParam);
	}
	return 0;
}

// Message handler for about box.
INT_PTR CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
	UNREFERENCED_PARAMETER(lParam);
	switch (message)
	{
	case WM_INITDIALOG:
		return (INT_PTR)TRUE;

	case WM_COMMAND:
		if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL)
		{
			EndDialog(hDlg, LOWORD(wParam));
			return (INT_PTR)TRUE;
		}
		break;
	}
	return (INT_PTR)FALSE;
}
